<template>
  <VPage>
    <VTable ref="tableRef" class="table-view" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption" />
      </template>
      <template #toolbar_btns>
        <!-- <VButton type="primary" icon="Plus" @click="openConfirmInput('add')">新增</VButton> -->
        <VButton type="primary" icon="Plus" @click="createPlan">新增</VButton>
        <VButton type="danger" icon="WarningFilled" @click="handleStatus">作废</VButton>
        <div class="ml-auto">汇总金额：{{ totalAmount }}</div>
      </template>
    </VTable>

    <!-- 弹窗 表单编辑 -->
    <ConfirmInput v-model="batchVisible" v-bind="getCurrentConfirm" @submit="handleConfirmSubmit" />
    <!-- 日志 -->
    <XLog ref="logRef" :api="stockingPlanLog" />
  </VPage>
</template>

<script setup lang="jsx">
import { stockingPlanList, stockingPlanCreate, stockingPlanVoided, stockingPlanLog, stockingPlanTotalAmount } from "@/api/plan"
import { ElMessage, ElMessageBox } from "element-plus"
import { onMounted, ref, toRefs } from "vue"

import XForm from "@/components/XForm/index.vue"
const tableRef = ref()
import ConfirmInput from "@/components/ConfirmInput/index.vue"
const batchVisible = ref(false)
const getCurrentConfirm = ref({})
// 日志
import XLog from "@/components/XLog"
const logRef = ref()

// 保存 弹窗 表单编辑
const handleConfirmSubmit = async (param) => {
  console.log(param)
  let res = {}
  switch (getCurrentConfirm.value.type) {
    case "add":
      res = await stockingPlanCreate(param)
      break
  }
  ElMessage.success(res.message)
  getCurrentConfirm.value = {}
  batchVisible.value = false
  query()
}

// 初始化时间
import { parseTime } from "@/utils/ruoyi"

// 开启 弹窗 表单编辑
const openConfirmInput = (type, params) => {
  let confirm = {}
  switch (type) {
    case "add":
      confirm = currentConfirmOpt.edit
      confirm.originOption = originOption.value
      confirm.form = {
        plan_name: `${parseTime(new Date(), "{y}-{m}-{d}")}备货计划`,
      }
      break
    default:
      break
  }
  confirm.type = type
  getCurrentConfirm.value = confirm
  batchVisible.value = true
}
const currentConfirmOpt = {
  // 新增
  edit: {
    title: "创建备货计划",
    formOptions: { inline: true, labelPosition: "top" },
    form: {},
    fieldOptions: [
      { field: "plan_name", label: "计划名称", style: { width: "512px" } },
      { field: "plan_type", label: "备货类型", type: "select", originField: "Plan.PlanStockingPlan.TypeEnum", style: { width: "248px" } },
      {
        label: "运营部门",
        field: "planning_department",
        type: "cascader",
        cascaderType: "department",
        placeholder: "运营部门",
        itemProps: { props: { emitPath: false, label: "name", value: "id", children: "sub" } },
        style: { width: "248px" },
        itemStyle: { marginRight: 0 },
      },
      {
        field: "remarks",
        label: "备注信息",
        placeholder: "备注信息",
        type: "textarea",
        style: { width: "512px" },
        autosize: { minRows: 4, maxRows: 6 },
      },
    ],
    rules: {
      plan_name: [{ required: true, message: "请输入计划名称", trigger: "blur" }],
      plan_type: [{ required: true, message: "请选择备货类型", trigger: "change" }],
      planning_department: [{ required: true, message: "请选择运营部门", trigger: "change" }],
    },
  },
}

// 获取已选中的行
const getSelectRow = () => {
  const getCheckboxRecords = tableRef?.value.$table.getCheckboxRecords()
  if (!getCheckboxRecords.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  return getCheckboxRecords.map((v) => v.id)
}

// 启用
const handleStatus = () => {
  const arr = getSelectRow()
  if (!arr.length) return false
  ElMessageBox.confirm(`此操作将 作废${arr.length}条数据, 是否继续?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "pmc-message-confirm-button",
  }).then(async () => {
    try {
      stockingPlanVoided({ id: arr }).then((res) => {
        ElMessage.success("操作成功")
        query()
      })
    } catch (e) {
      throw Error(e)
    }
  })
}
// 查询
const query = () => {
  tableRef?.value.query()
}
const formOption = ref({ inline: true })

const fieldList = ref([
  {
    field: "timeRange",
    type: "dateTimeRangeNorm",
    select: [
      { label: "添加时间", value: "created_at" },
      { label: "审核时间", value: "reviewed_at" },
    ],
    style: { width: "360px" },
  },
  { placeholder: "备货计划单", field: "pr_number", type: "textarea", style: { width: "200px" } },

  {
    field: "plan_type",
    type: "select",
    originField: "Plan.PlanStockingPlan.TypeEnum",
    options: { placeholder: "计划类型" },
    style: { width: "120px" },
  },
  {
    field: "planning_department",
    type: "cascader",
    cascaderType: "department",
    placeholder: "运营部门",
    itemProps: {
      props: {
        emitPath: false,
        multiple: true,
        label: "name",
        value: "id",
        children: "sub",
      },
    },
    style: { width: "200px" },
  },

  {
    field: "plan_status",
    type: "select",
    originField: "Plan.PlanStockingPlan.PlanStatusEnum",
    options: { placeholder: "计划状态" },
    style: { width: "120px" },
  },
])

import { enumGet } from "@/api"
//获取下拉数据
onMounted(() => {
  getOption()
})

// 枚举 数据
const originOption = ref({})
// 获取下拉数据
const getOption = async () => {
  const { data } = await enumGet({
    name: fieldList.value.filter((v) => v.originField).map((v) => v.originField),
  })
  for (const key in data) {
    originOption.value[key] = data[key]
  }
}

// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: { timeRange: { type: "created_at", value: "", range: true } },
  },
  rowConfig: { height: "76" },
  columns: [
    { type: "checkbox", fixed: "left", width: 40 },
    {
      title: "PR单",
      width: 150,
      slots: {
        default: ({ row }) => <VText value={row.pr_number} line={1} type="link" />,
      },
    },
    { title: "计划名称", field: "plan_name", width: 180 },
    { title: "备货类型", field: "plan_type_text", width: 80 },
    { title: "计划部门", field: "planning_department_name", width: 160 },
    { title: "状态", field: "plan_status_text", width: 80 },
    { title: "备货金额/RMB", field: "stocking_amount", width: 120 },
    {
      title: "备货明细",
      width: 180,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="text-[14px] font-bold">
              {row?.statistics_review_status[0].review_status_text}: {row?.statistics_review_status[0].count}
            </div>

            <div class="grid grid-cols-2 gap-x-2">
              {row?.statistics_review_status?.map((item, i) => (i != 0 ? <VText title={item.review_status_text} value={item.count || "0"} line={1} class="text-red" /> : ""))}
            </div>
          </div>
        ),
      },
    },

    {
      title: "下单/发货",
      width: 120,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="采购下单" value={row.purchase_order_placement ? `${row.purchase_order_placement}%` : ""} line={1} />
            <VText title="备库发货" value={row.warehouse_stock_dispatch ? `${row.warehouse_stock_dispatch}%` : ""} line={1} />
          </div>
        ),
      },
    },

    { title: "备注", field: "remarks", width: 150 },
    { title: "添加类型", field: "addition_type_text", width: 80 },
    {
      title: "人员信息",
      width: 120,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="添加" value={row.created_by_text} line={1} />
            <VText title="审核" value={row.reviewed_by_text} line={1} />
          </div>
        ),
      },
    },
    {
      title: "时间信息",
      width: 180,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="添加" value={row.created_at} line={1} />
            <VText title="审核" value={row.updated_at} line={1} />
          </div>
        ),
      },
    },

    {
      title: "操作",
      width: 160,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return [
            <div>
              <el-button link type="primary" onClick={() => ruleEdit(row)}>
                查看
              </el-button>
              <el-button link type="primary" onClick={() => gotoDtl(row)}>
                编辑
              </el-button>

              <el-button link type="primary" onClick={() => logRef?.value.open({ id: row.id })}>
                日志
              </el-button>
            </div>,
          ]
        },
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        let params = { ...form, page: page.pageNum, page_size: page.pageSize }
        let keys = ["pr_number"]
        keys.forEach((key) => {
          params[key] = params[key]?.split("\n")?.filter((v) => !!v.trim())
          params[key] = params[key]?.map((v) => v.trim())
        })
        stockingPlanTotalAmount(params).then((res) => {
          totalAmount.value = res.data.total_amount
        })
        return stockingPlanList(params)
      },
    },
  },
})
const totalAmount = ref(0)
const router = useRouter()
// 查看
const ruleEdit = (row) => {
  router.push(`/plan/stockUpPlan/view/${row.id}`)
}
// 编辑
const gotoDtl = (row) => {
  router.push(`/plan/stockUpPlan/edit/${row.id}`)
}
// 新增
const createPlan = () => {
  router.push(`/plan/stockUpPlan/add`)
}
</script>
<style lang="scss" scoped></style>
